﻿using AGooday.AgChat.Api.Models;
using Microsoft.EntityFrameworkCore;

namespace AGooday.AgChat.Api.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
        }

        public DbSet<User> Users { get; set; }
        public DbSet<Friendship> Friendships { get; set; }
        public DbSet<Group> Groups { get; set; }
        public DbSet<GroupMember> GroupMembers { get; set; }
        public DbSet<Message> Messages { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Configure relationships
            modelBuilder.Entity<Friendship>()
                .HasOne(f => f.User)
                .WithMany(u => u.Friends)
                .HasForeignKey(f => f.UserId)
                .OnDelete(DeleteBehavior.Restrict);

            modelBuilder.Entity<Friendship>()
                .HasOne(f => f.Friend)
                .WithMany()
                .HasForeignKey(f => f.FriendId)
                .OnDelete(DeleteBehavior.Restrict);

            modelBuilder.Entity<Message>()
                .HasOne(m => m.Sender)
                .WithMany(u => u.Messages)
                .HasForeignKey(m => m.SenderId)
                .OnDelete(DeleteBehavior.Restrict);

            modelBuilder.Entity<Message>()
                .HasOne(m => m.Receiver)
                .WithMany()
                .HasForeignKey(m => m.ReceiverId)
                .OnDelete(DeleteBehavior.Restrict);

            modelBuilder.Entity<Message>()
                .HasOne(m => m.Group)
                .WithMany(g => g.Messages)
                .HasForeignKey(m => m.GroupId)
                .OnDelete(DeleteBehavior.Restrict);

            //modelBuilder.Entity<GroupMember>()
            //    .HasOne(gm => gm.Group)
            //    .WithMany(g => g.Members)
            //    .HasForeignKey(gm => gm.GroupId)
            //    .OnDelete(DeleteBehavior.Cascade);

            //modelBuilder.Entity<GroupMember>()
            //    .HasOne(gm => gm.User)
            //    .WithMany(u => u.Groups)
            //    .HasForeignKey(gm => gm.UserId)
            //    .OnDelete(DeleteBehavior.Cascade);


            modelBuilder.Entity<GroupMember>(entity =>
            {
                entity.HasOne(gm => gm.Group)
                      .WithMany(g => g.Members)
                      .HasForeignKey(gm => gm.GroupId)
                      .OnDelete(DeleteBehavior.Cascade); // 保留对 Groups 的级联删除

                entity.HasOne(gm => gm.User)
                      .WithMany(u => u.Groups)
                      .HasForeignKey(gm => gm.UserId)
                      .OnDelete(DeleteBehavior.Restrict); // 将对 Users 的删除行为改为 Restrict
            });
        }
    }
}
